package com.xjtu.conan.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.conan.entity.ArticleInfo;
import com.xjtu.conan.entity.NewsInfo;
import com.xjtu.conan.exception.MyException;
import com.xjtu.conan.mapper.ArticleInfoMapper;
import com.xjtu.conan.mapper.NewsInfoMapper;
import com.xjtu.conan.service.ArticleInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 话题表 服务实现类
 * </p>
 *
 * @author 一只黑猩猩
 * @since 2021-04-19
 */
@Service
public class ArticleInfoServiceImpl extends ServiceImpl<ArticleInfoMapper, ArticleInfo> implements ArticleInfoService {

    @Autowired
    private ArticleInfoMapper articleInfoMapper;

    @Override
    public List<ArticleInfo> getAllArticleInfo(int current, int size) {
        Page<ArticleInfo> page = new Page<>(current, size);
        articleInfoMapper.selectPage(page, null);
        System.out.println(page.getTotal());
        return page.getRecords();
    }

    @Override
    public ArticleInfo getArticleBynId(Long aid) {
        ArticleInfo articleInfo = articleInfoMapper.selectById(aid);
        if (articleInfo == null) {
            throw new MyException(500, "不存在该话题！");
        }
        return articleInfo;
    }

    @Override
    public Long addArticleInfo(ArticleInfo articleInfo) throws IOException {
        try {
            if (articleInfoMapper.insert(articleInfo) == 1) {
                return articleInfo.getAid();
            } else
                throw new MyException(500, "添加话题失败！");
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(500, "添加话题失败！");
        }
    }

    @Override
    public Long updateArticleInfo(ArticleInfo articleInfo) {
        try {
            if (articleInfoMapper.updateById(articleInfo) == 1) {
                return articleInfo.getAid();
            } else
                throw new MyException(500, "更新话题失败！");
        } catch (Exception e) {
            throw new MyException(500, "更新话题失败！");
        }
    }

    @Override
    public int deleteArticleInfo(Long aid) {
        try {
            return articleInfoMapper.deleteById(aid);
        } catch (Exception e) {
            throw new MyException(500, "删除话题失败！");
        }
    }

    @Override
    public int getTotal()  {
        return articleInfoMapper.selectCount(null);
    }

}
